package com.mars.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineCount implements HttpSessionListener {
    //创建Session监听：每创建一个Session就出发一次
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");

        if(onlineCount==null){
            onlineCount = new Integer(1);

        }else{
            int count = onlineCount;
            onlineCount = count+1;
        }
        //set方法：如果没有该属性，将自动创建
        ctx.setAttribute("OnlineCount",onlineCount);
    }
    //每次销毁Session触发
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
        //删完后没了的话，就把数量置为0
        if(onlineCount==null){
            onlineCount = new Integer(0);

        }else{
            //删完部位空就-1
            int count = onlineCount;
            onlineCount = count-1;
        }

        ctx.setAttribute("OnlineCount",onlineCount);
    }

//    Session销毁：
//    1、自动销毁
//    2、手动销毁

}
